<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-02-28
 * Time: 23:38
 */

class tcp
{
    const HOST = '0.0.0.0';
    const PORT = 8000;
    public $serv = null;

    public function __construct()
    {
        /**
         * $host
         *
         * $port
         *
         * $mode 运行模式 SWOOLE_PROCESS(多进程模式 默认) SWOOLE_BASE(基本模式)
         *
         * $socket_type 指定socket类型 支持TCP、UDP、TCP6、UDP6、UnixSocket Stream/Dgram 6种
         */
        $this->serv = new swoole_server(self::HOST, self::PORT);
        //设置参数
        $this->serv->set([
            'worker_num' => 8, //worker进程数 CPU核数的1-4倍
            'max_request' => 2000 //表示worker进程在处理完n次请求后结束运行
        ]);
        //注册connect receive close方法
        $this->serv->on('connect', [$this, 'onConnect']);
        $this->serv->on('receive', [$this, 'onReceive']);
        $this->serv->on('close', [$this, 'onClose']);
        //启动服务
        $this->serv->start();
    }
    /**
     * $fd 客户端连接的唯一标识
     * $from_id 线程ID
     */
    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client: {$from_id}-{$fd}Connect.\n";
    }

    public function onReceive($serv, $fd, $from_id, $data)
    {
        $msg = json_decode($data, true);
        switch ($msg['type']) {
            case 1:
                $serv->send($fd, 'Connect success!' . PHP_EOL);
                break;
            case 2:
                $serv->send($fd, $msg['msg'] . mt_rand(100, 999) . PHP_EOL);
                break;
            default:
                $serv->send($fd, 'type fail' . PHP_EOL);
                break;
        }
    }

    public function onClose($serv, $fd)
    {
        echo "Client: Close {$fd}.\n";
    }
}

$serv = new tcp();